<template>
  <div class="dashboard-container"
    v-loading="loading"
    element-loading-text="拼命解析中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    @dragover="fileDragover" @drop="fileDrop"
  >
    <!-- <div class="dashboard-text">name: {{ name }}</div> -->
    <div class="titleText">
      <h1>Excel翻译成lua脚本在线版</h1>
    </div>
    <div class="titleText hui">
      只能上传Excel文件
    </div>
    <el-upload
      class="upload-demo"
      ref="upload" 
      drag
      :multiple='false'
      :auto-upload='false'
      :file-list="fileList"
      :limit="10"
      :before-remove="beforeRemove"
      :on-change="handleChange"
      action="https://jsonplaceholder.typicode.com/posts/"
    >
      <!-- <i class="el-icon-upload"></i> -->
      
      <img src="@/assets/file.png" alt="" srcset="">
      <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
    </el-upload>

    <div style="max-width: 900px; margin: 10px auto;">

      <div @click="ifBy = !ifBy" class="lan">
        在线同步表格
      </div> 

      <h1 class="marginTop26" v-if="ifBy">1. 设置通用表里的 key (module[这里使用表格的那个值])</h1>

      <el-input v-if="ifBy" v-model="input" @change="inputChange2" placeholder="请输入列头数据依据"></el-input>

      <br>
      <br>

      <el-input v-if="ifBy" v-model="miyao" 
        placeholder="请输入密钥">
      </el-input>
      <br>
      <br>
      <el-input v-if="ifBy" v-model="biaoToken" 
        placeholder="请输入表格Token">
        <el-button @click="getSpreadsheets"  slot="append" icon="el-icon-search"></el-button>
      </el-input>
      <br>
      <br>
      <div v-if="ifBy && spreadsheets.sheets">
      <h1>表格名称：{{spreadsheets.properties.title}}
          <!-- {{time}} -->
      </h1> 
        <br>
        <div class="lan" @click="getSpreadsheetsValue(i.sheetId,i.rowCount)" v-for="(i,index) in spreadsheets.sheets" :key="index">
          {{i.title}}
          <br>
          <br>
        </div>
      </div>
      <el-button v-show="sheetId" class="tag-read2" type="primary"  :data-clipboard-text="sheetText" @click="copy('.tag-read2')">复制代码</el-button>
      <div v-show="sheetId" class="textarea_box" contenteditable = "true" id="sheetText" v-html="sheetText" style="white-space: pre-wrap;"></div>

    </div>

    <h1 class="marginTop26" v-if="excelFile">1. 设置通用表里的 key (module[这里使用表格的那个值])</h1>

    <el-input v-if="excelFile" v-model="input" @change="inputChange" placeholder="请输入列头数据依据"></el-input>

    <br>
    <br>
    <!-- {{htmlData}} -->
    <h1 class="marginTop26" v-if="excelFile">3. 选择Excel 工作表表单列表</h1>
    <!-- {{input}} {{show}} -->
    <div v-for="(i,index) in htmlData" class="excelTitle marginTop26" :class="{
      'redText':show == i.id
    }"  :key="'01'+index" @click="show = i.id">
      <h4>{{i.wsname}}</h4> 
    </div>
    <!-- <h4>{{htmlData[index].wsname}}</h4> -->
    <div v-for="(i,index) in htmlData"  :key="'02'+index" v-show="show == i.id">
      <div class="marginTop26" >
        <el-button class="tag-read" type="primary"  :data-clipboard-text="i.text" @click="copy('.tag-read')">复制代码</el-button>
        <el-button @click="selectText(i.id)">全选代码</el-button>
        ( ps:下方代码可在线修改 )
      </div>
      <!-- <h4 @click="cloneCode(i.text)">复制</h4> -->
      <!-- <prism-editor :code="i.text" language="js"></prism-editor> -->
      <div class="textarea_box" contenteditable = "true" :id="i.id" v-html="i.text" style="white-space: pre-wrap;"></div>
    </div>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import axios from 'axios'
import XLSX from 'xlsx'
import Clipboard from 'clipboard'
import { json } from 'body-parser'

export default {
  name: 'Dashboard',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  components: {
    // PrismEditor
  },
  data(){
    return{
      excelSheets:{},

      dialogTableVisible:false,

      ifShow:false,
      show:'',
      input:'',
      textarea:'',
      htmlData:[],

      excelFile:null,
      fileList: [],
      loading:false,

      // token:'4YWaUiyECWbSjQ0ZPQ65YkgbyVLgAtUu4yKc5U8j',
      ifBy:false,
      tenant_access_token:'',
      // 表格token
      biaoToken:'',
      // 电子表格
      spreadsheets:{},
      // 表格id
      sheetId:'',
      sheetText:'',
      sheetData:'',
      // 密钥 dream
      miyao:'',

      time:0
    }
  },
  mounted(){
    // GET /user
    this.postFun('/user','GET',{}).then(res=>{
      console.log('/user',res)
    })
    
    let str = ''
    // 飞书开放平台 凭证和基本信息 应用凭证
    let params = {
      "app_id": "cli_a225774de838500b",
      "app_secret": "CtpnHHHo9NXBYaNhxiTzbeMBVXBesl1L"
    }
    // 获取 app_access_token '/open-apis/auth/v3/app_access_token/internal'
    // let tenant_access_token = ''
    // 电子表格 token
    // let biaoToken = 'shtcnvQOaaYhmNzolxkGqiNYq1g'

    this.getToken()

    setInterval(res=>{
      this.time-- 
    },1000)

    setTimeout(() => {
      this.miyao = localStorage.getItem('miyao')
      this.biaoToken = localStorage.getItem('biaoToken')
      this.input = localStorage.getItem('inputText')

      this.tenant_access_token = this.$store.getters.tenant_access_token
    }, 1000);
  },
  methods:{
    getToken(){
    },
    getSpreadsheets(){
      if (this.miyao != 'dream') {
        return
      }
      let biaoToken = this.biaoToken

      localStorage.setItem('biaoToken',biaoToken)
      localStorage.setItem('miyao',this.miyao)
      localStorage.setItem('inputText',this.input || '')

      this.$Leancloud.dataRequest.postGet({
        url:`https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/${biaoToken}/metainfo`,
        headers:{"Authorization": 'Bearer '+ this.tenant_access_token},
        data: {
        }
      }).then(res=>{
        console.log('表信息',res)
        this.spreadsheets = res.data
         // https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/shtcngNygNfuqhxTBf588jwgWbJ/values/Q7PlXT!A3:D200
      })
    },
    // 查询在线表格信息
    setSheetText(){
      let  ws =  this.sheetData
      // ---- 注释
      // -- module['注释'] = ${JSON.stringify(ws[0])}
        this.sheetText = 
        `local module = {}
                      `
        // ---- 内容
          for (let i = 1; i < ws.length; i++) {
                const element = ws[i];
                
                this.sheetText += `
  module[${this.input?"'"+element[this.input]+"'":i}] = ${JSON.stringify(element)}`
              }
        // ---- 结尾
                      // 特殊样式不要更改
                      this.sheetText += `

 return module`

              // console.log('插入数据',this.sheetText);
            //  {"
              this.sheetText = this.sheetText.replace(/":/g,'"=').replace(/{"/g,"{").replace(/,"/g,",").replace(/"=/g,"=").replace(/"{/g,"{").replace(/}"/g,"}").replace(/=\/\//g,"://")
              // console.log('显示内容',this.sheetText)
    },
    async getSpreadsheetsValue_post(sheetId,rowState,rowCount,sheet_data0){
      
      // console.log('查询', rowState,rowCount)

      var sheet_data_ = null
      var sheet_data0_ = null
      this.sheetId = sheetId
      let biaoToken = this.biaoToken
      const result = await this.$Leancloud.dataRequest.postGet({
        url:`https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/${biaoToken}/values/${sheetId}!A${rowState}:ZZ` + (rowState + rowCount),
        headers:{"Authorization": 'Bearer '+ this.tenant_access_token},
        data: {
          // "ranges":['0b1422!A1:B100']
        }
      }).then(res=>{
        // console.log('表格 sheets 信息',res,res.data,res.data.valueRange)
        let data = res.data.valueRange.values
        let ws = []
        if (sheet_data0) {
          data = [sheet_data0, ...data]
        }
        // console.log(' -- 头一行 -- ',data[0])
        // 列
        for (let index = 1; index < data.length; index++) {
          const element = data[index];
          // 不是都是null
          const hasPermission = element.some(role => {
              return role != null
          })
          if (hasPermission) {
            let obj = {}
            // 横
            for (let index2 = 0; index2 < element.length; index2++) {
              const element2 = element[index2];
              // 第一行属性
              // console.log(' -- 属性 -- ',data[0][index2])
              if (data[0][index2] && element2) {
                obj[data[0][index2]] = element2
              }
            }
            ws.push(obj)
          }
        }
        // console.log('第一行属性',ws)
        sheet_data_ = ws
        sheet_data0_ = data[0]
      })
      // console.log('sheet_data_ ',sheet_data_)
      return [sheet_data_,sheet_data0_]
    },
    async getSpreadsheetsValue(sheetId,rowCount){
      if (this.time>0) {
        return
      }
      this.time = 3

      var num = rowCount
      var rowState = 1
      var sheet_data = []
      var sheet_data0 = null
      var data0 = null

      // console.log('总共 多少条 ', num)

      while (num > 0) {

        // num > 1500 ? 1500 : num - 1
        var [data,data0] = await this.getSpreadsheetsValue_post(sheetId,rowState,1500,sheet_data0)
        // console.log('结果', data,data0)
        if (rowState == 1) {
          sheet_data0 = data0
        }

        sheet_data = [...sheet_data,...data]

        num = num - 1500

        rowState = rowState + 1500

      }

      // console.log('结果 all ', sheet_data)

      this.sheetData = sheet_data
      this.setSheetText()
    },

    postFun(url,method,data){
      let url01 = 'https://suibianba.yuque.com/api/v2'
      return axios({
        method: method,
        headers: { 
          "Content-Type": "application/json",
          "User-Agent": "sbb",
          "X-Auth-Token": this.token
        },
        data,
        url:url01 + url,
      })
    },
    tokenChange(){

    },
    ifDialogShow(){
      this.dialogTableVisible = true
    },
    openFile(){
      // this.$refs.upload.clearFiles()
      this.$refs.upload.$children[0].handleClick();
    },
    // 拖拽上传
    fileDragover (e) {
      e.preventDefault()
      console.log('拖拽上传',e)
    },
 
    fileDrop (e) {
      e.preventDefault()
      const file = e.dataTransfer.files[0] // 获取到第一个上传的文件对象
    },
    onDrag (e) {
      // console.log('1. onDrag e ',e)
      e.stopPropagation();
      e.preventDefault();
      this.ifShow = false
    },
    onDrag2 (e) {
      // console.log('2. onDrag e ',e)
      e.stopPropagation();
      e.preventDefault();
      this.ifShow = true
    },
    onDrop (e) {
      console.log('3. onDrop e ',e)
      e.stopPropagation();
      e.preventDefault();
      let file = e.dataTransfer.files[0]
      this.readExcel(e)
    },
    handleChange(file, fileList) {
      console.log(' 选择文件 ',file, fileList)
      var event = event || window.event;
      this.fileList = [file]
      this.readExcel(file.raw);
      this.excelFile = file.raw
    },
    beforeRemove(file, fileList) {
      console.log(' 移除文件 ',file, fileList)
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    copy (cls) {
      let clipboard = new Clipboard(cls)
      clipboard.on('success', e => {
          console.log('复制成功',clipboard)
          this.$message({
            message: '已复制到剪切板，Ctrl + v去吧！！',
            type: 'success'
          });
          //  释放内存
        clipboard.destroy();
      })
      clipboard.on('error', e =>{
        // 不支持复制
        console.log('该浏览器不支持复制',clipboard)
        // 释放内存
        clipboard.destroy()
      })
    },
    cloneCode(text){
              
      // const
      //   input = document.createElement(
      //     'input'
      //   );

      // document.body.appendChild(input);

      // input.setAttribute(
      //   'value'
      //   ,
      //   text
      // );

      // input.select();


      // if
      //   (document.execCommand(
      //     'copy'
      //   )) {

      //   document.execCommand(
      //     'copy'
      //   );


      //   this.$message({
      //     message: '已复制到剪切板，Ctrl + v去吧！！',
      //     type: 'success'
      //   });

      // }

      // document.body.removeChild(input);
            
    },
    inputChange2(e){
        console.log(e)
        this.setSheetText()
    },

    inputChange(e){
        console.log(e)
        this.readExcel(this.excelFile);
        this.readExcel(this.excelFile);
    },
    selectText(element) {
        var text = document.getElementById(element);
        if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(text);
            range.select();
        } else if (window.getSelection) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
            /*if(selection.setBaseAndExtent){
                selection.setBaseAndExtent(text, 0, text, 1);
            }*/
        } else {
            alert("none");
        }
    },
    //表格导入
    readExcel(e) {
        this.loading = true
        var that = this;
        const files = [e] //-- e.target.files;
        console.log('表格',files);

        if(files.length<=0){//如果没有文件名
          return false;
        }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
          this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
          return false;
        }

        console.log('-- 内容 --');
        
        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: 'binary'
            });
            console.log('表格具体信息',workbook)
            // const wsname = workbook.SheetNames[0];//取第一张表
            // let [index,value] of [‘a’,‘b’,‘c’].entries()
            that.htmlData  = []
            for (const [index,value] of workbook.SheetNames.entries()) {
              let wsname = value
              console.log('表格',index,value)
              const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
              console.log('表格内容 ',ws);

              that.htmlData[index] = {}
              that.htmlData[index].id = 'id_' + index
              that.htmlData[index].wsname = wsname
              that.htmlData[index].text = 
`local module = {}

	-- module['注释'] = ${JSON.stringify(ws[0])}
              `
              for (let i = 1; i < ws.length; i++) {
                const element = ws[i];
                
                that.htmlData[index].text += `
	module[${that.input?"'"+element[that.input]+"'":i}] = ${JSON.stringify(element)}`


              }
              // 特殊样式不要更改
              that.htmlData[index].text += `
return module`

              // console.log('插入数据',JSON.stringify(obj));
            //  {"
              that.htmlData[index].text = that.htmlData[index].text.replace(/:/g,"=").replace(/{"/g,"{").replace(/,"/g,",").replace(/"=/g,"=").replace(/"{/g,"{").replace(/}"/g,"}").replace(/=\/\//g,"://")
              console.log('显示内容',that.htmlData[index].text)
            }
            console.log('输出信息',that.htmlData)
            that.show = that.htmlData[0].id
            
            this.loading = false
            // that.outputs = [];//清空接收数据
            // for(var i= 0;i<ws.length;i++){
            // var sheetData = {
            //     address: ws[i].addr,
            //     value: ws[i].value
            // }
            // that.outputs.push(sheetData);
            // }
            // this.$refs.upload.value = '';
 
           
        };
        // fileReader.readAsBinaryString(files[0]);
        fileReader.readAsArrayBuffer(files[0]);
    },

    // 六安数据导入
    readExcel2(e) {//表格导入
        this.loading = true
        var that = this;
        const files = [e] //-- e.target.files;
        console.log('表格',files);

        if(files.length<=0){//如果没有文件名
          return false;
        }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){
          this.$Message.error('上传格式不正确，请上传xls或者xlsx格式');
          return false;
        }

        console.log('-- 内容 --');
        
        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: 'binary'
            });
            console.log('表格具体信息',workbook)
            // const wsname = workbook.SheetNames[0];//取第一张表
            // let [index,value] of [‘a’,‘b’,‘c’].entries()
            that.htmlData  = []
            for (const [index,value] of workbook.SheetNames.entries()) {
              let wsname = value
              console.log('表格',index,value)
              const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]);//生成json表格内容
              console.log('表格内容 ',ws);

              // 只查看第一个表格
              if(index != 0){
                break
              }

              // 表格第一行设置为0123456789
              let contentObj = {}
              
              // 0 2 4 6 8
              for (const item of ws) {
                // contentObj
                if(!contentObj[item[0]]){
                  if(!item[1]){
                    console.log(item)
                  }
                  contentObj[item[0]] = {
                    "text":item[0],
                    "info":item[1].replace(/\n/g, "\r\n"),
                    "children":{},
                  }
                }
                // 社区党总支
                if(!contentObj[item[0]].children[item[2]]){
                  contentObj[item[0]].children[item[2]] = {
                    "text":item[2],
                    "info":item[3].replace(/\n/g, "\r\n"),
                    "children":{},
                  }
                }
                // 小区党支部
                if(item[4] && !contentObj[item[0]].children[item[2]].children[item[4]]){
                  contentObj[item[0]].children[item[2]].children[item[4]] = {
                    "text":item[4],
                    "info":item[5].replace(/\n/g, "\r\n"),
                    "children":{},
                  }
                }
                // 网格党小组
                if(item[6] && !contentObj[item[0]].children[item[2]].children[item[4]].children[item[6]]){
                  contentObj[item[0]].children[item[2]].children[item[4]].children[item[6]] = {
                    "text":item[6],
                    "info":item[7].replace(/\n/g, "\r\n"),
                    "children":{},
                  }
                }
                // 党员中心户
                if(item[8] && !contentObj[item[0]].children[item[2]].children[item[4]].children[item[6]].children[item[8]]){
                  contentObj[item[0]].children[item[2]].children[item[4]].children[item[6]].children[item[8]] = {
                    "text":item[8],
                    "info":item[9].replace(/\n/g, "\r\n"),
                    "children":{},
                  }
                }
              }

              that.htmlData[index] = {}
              that.htmlData[index].id = 'id_' + index
              that.htmlData[index].wsname = wsname
              that.htmlData[index].text = JSON.stringify(contentObj)
              
            }
            console.log('输出信息',that.htmlData)
            that.show = that.htmlData[0].id
            
            this.loading = false
            // that.outputs = [];//清空接收数据
            // for(var i= 0;i<ws.length;i++){
            // var sheetData = {
            //     address: ws[i].addr,
            //     value: ws[i].value
            // }
            // that.outputs.push(sheetData);
            // }
            // this.$refs.upload.value = '';
           
        };
        // fileReader.readAsBinaryString(files[0]);
        fileReader.readAsArrayBuffer(files[0]);
    },

  }
}
</script>

<style lang="scss" >
    .el-upload.el-upload--text{
      width: 100%;
    }
    .el-upload-dragger{
      width: 100%;
      height: auto;
      padding: 26px;
      img{
        width: 150px;
      }
    }
</style>
<style lang="scss" scoped>
  .lan{
    color: #0077ff;
  }
  .marginTop26{
    margin: 26px 0;
  }

  .titleText{
      margin-top: 0;
      font-size: 38px;
      font-family: Microsoft YaHei-Bold,Microsoft YaHei,HelveticaNeue;
      color: #131a22;

      margin-bottom: 30px;
      margin-top: 30px;
      text-align: center;
  }
  .hui{
    color: #999;
    font-size: 18px;
  }
  .upload-demo{
    display: inline-block;
    max-width: 900px;
    margin: 10px auto;
    background: #f5f7fb;
    border-radius: .02rem .02rem .02rem .02rem;
    padding: 26px;
    opacity: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
  }
  .el-dialog__wrapper{
    z-index: 1000000000000000000!important;
  }
  .v-modal{
    z-index: 100000000!important;
  }
  .dialogTableVisible{
    color: cornflowerblue;
    width: 300px;
    line-height: 40px;
    background-color: #fff;
    position: absolute;
    top: 10px;
    right: 0px;
    z-index: 100;

    display: flex;
    justify-content: space-around;
  }
  .ifShow{
    border: 1px solid #a7a6a6;
  }
  .dashboard-container{
    margin: 0!important;
    padding: 26px 26px 400px;
  }

.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
.excelTitle{
  color:cadetblue;
}
.redText{
  color: rebeccapurple;
}
</style>
